package com.example.projectmanagement.controller;

import com.example.projectmanagement.model.Role;
import com.example.projectmanagement.service.UserRoleService;
import com.example.projectmanagement.service.UserService;
import com.example.projectmanagement.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/user-roles")
@CrossOrigin
public class UserRoleController {
    
    @Autowired
    private UserRoleService userRoleService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private RoleRepository roleRepository;
    
    /**
     * 为用户分配角色
     */
    @PostMapping("/{userId}/roles/{roleId}")
    public ResponseEntity<Void> assignRoleToUser(@PathVariable Long userId, @PathVariable Long roleId) {
        // 检查是否尝试为用户分配ADMIN角色
        Optional<Role> roleOpt = roleRepository.findById(roleId);
        if (roleOpt.isPresent() && "ADMIN".equals(roleOpt.get().getRoleName())) {
            throw new RuntimeException("不能为用户分配系统管理员角色");
        }
        
        userRoleService.assignRoleToUser(userId, roleId);
        return ResponseEntity.ok().build();
    }
    
    /**
     * 获取用户的所有角色
     */
    @GetMapping("/{userId}/roles")
    public ResponseEntity<List<Role>> getRolesByUserId(@PathVariable Long userId) {
        List<Role> roles = userRoleService.getRolesByUserId(userId);
        return ResponseEntity.ok(roles);
    }
    
    /**
     * 移除用户的角色
     */
    @DeleteMapping("/{userId}/roles/{roleId}")
    public ResponseEntity<Void> removeRoleFromUser(@PathVariable Long userId, @PathVariable Long roleId) {
        // 检查是否尝试移除用户的ADMIN角色
        Optional<Role> roleOpt = roleRepository.findById(roleId);
        if (roleOpt.isPresent() && "ADMIN".equals(roleOpt.get().getRoleName())) {
            // 检查用户是否拥有ADMIN角色
            List<Role> userRoles = userService.getUserRoles(userId);
            boolean isAdmin = userRoles.stream()
                    .anyMatch(role -> "ADMIN".equals(role.getRoleName()));
            
            if (isAdmin) {
                throw new RuntimeException("不能移除用户的系统管理员角色");
            }
        }
        
        userRoleService.removeRoleFromUser(userId, roleId);
        return ResponseEntity.ok().build();
    }
}